package com.zhiyou100.taxi.acction;

import com.github.pagehelper.PageInfo;
import com.zhiyou100.taxi.entity.User;
import com.zhiyou100.taxi.service.UserService;
import com.zhiyou100.taxi.utils.FileNameUtil;
import com.zhiyou100.taxi.utils.MD5Utils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;

/**
 * @author zhaokuii11@163.com
 * @create 2021-11-23 19:03
 * @Description
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/login.action")
    public String login(User user, Model model, HttpSession session) {
        User loginUser = userService.getUserByNameAndPwd(user);
        if (loginUser != null) {
            session.setAttribute("loginUser", loginUser);
            return "redirect:/index.action";
        } else {
            model.addAttribute("message", "用户名或者密码错误");
            return "login";
        }
    }

    @RequestMapping("/logout.action")
    public String logout(HttpSession session) {
        //让 session 失效
        session.invalidate();
        return "login";
    }

    @RequestMapping("/show.action")
    public String show() {
        return "forward:/user/page.action";
    }

    @RequestMapping("/page.action")
    public String page(Integer pageNum, HttpServletRequest request) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<User> userPageInfo = userService.getPage(pageNum);
        request.getSession().setAttribute("userPageInfo", userPageInfo);
        return "system/userList";
    }

    @RequestMapping("/save.action")
    public String save(User user, HttpServletRequest request) {
        user.setUserPhoto("/imgs/user/" + saveFilename);
        user.setUserId(userService.getPrimaryKey());
        user.setUserPwd(MD5Utils.string2MD5(user.getUserPwd()));
        int num = userService.insert(user);
        if (num > 0) {
            request.setAttribute("msg", "保存成功");
        } else {
            request.setAttribute("msg", "保存失败");
        }
        //将 saveFilename 制空
        saveFilename = "";
        return "forward:/user/page.action";
    }

    String saveFilename = "";

    //ajax 页面回显图片
    @ResponseBody
    @RequestMapping("/ajaxImg.action")
    public Object ajaxImg(MultipartFile userPhoto, HttpServletRequest request) {//pimage 要和 图片上传页面的image标签的 name属性一致
        //1. 提取生成文件名 uuid + 上传图片的后缀
        saveFilename = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(userPhoto.getOriginalFilename());
        System.out.println("保存的图片====>saveFilename = " + saveFilename);
        //2. 得到项目中图片存储的路径
        String path = request.getServletContext().getRealPath("/imgs/user");
        //3. 转存
        //D:\code\mimissm\image_big\4321898f83924.png
        try {
            userPhoto.transferTo(new File(path + File.separator + saveFilename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("图片路径===》path = " + path + "\\" + saveFilename);
        //返回客户端 json对象,封装图片的路径,为了在页面实现立即回显
        JSONObject object = new JSONObject();
        //放入上传图片的名称
        object.put("imgurl", saveFilename);
        //如果 json对象返回必须 toString,转换特点
        return object.toString();
    }

    @RequestMapping("/deleteBatch.action")
    public String deleteBatch(String userIds, HttpServletRequest request) {
        String[] split = userIds.split(",");
        HashSet<String> set = new HashSet<>(Arrays.asList(split));
        int num = userService.deleteByPrimaryKeys(set);
        if (num > 0) {
            request.setAttribute("msg", "删除成功");
        } else {
            request.setAttribute("msg", "删除失败");
        }
        return "forward:/user/page.action";
    }

    @RequestMapping("/deleteOne.action")
    public String delete(String userId, HttpServletRequest request) {
        int num = userService.deleteByPrimaryKey(userId);
        if (num > 0) {
            request.setAttribute("msg", "删除成功");
        } else {
            request.setAttribute("msg", "删除失败");
        }
        return "forward:/user/page.action";
    }

    @RequestMapping("/getOne.action")
    public String getOne(String userId, HttpServletRequest request) {
        User user = userService.getOneByPrimaryKey(userId);
        request.setAttribute("user", user);
        return "system/user-edit";
    }

    @RequestMapping("/update.action")
    public String update(Boolean pwdIsChange, User user, HttpServletRequest request) {
        if (!saveFilename.equals("")) { //如果不为空说明已经修改了图片
            System.out.println("saveFilename = " + saveFilename);
            user.setUserPhoto("/imgs/user/" + saveFilename);
        }
        if (pwdIsChange) {
            user.setUserPwd(MD5Utils.string2MD5(user.getUserPwd()));// 把密码进行加密
        }
        System.out.println("更新的用户===============>user:" + user.getUserPhoto() + user);
        int num = userService.updateByPrimaryKey(user);
        if (num > 0) {
            request.setAttribute("msg", "更新成功");
        } else {
            request.setAttribute("msg", "更新失败");
        }
        //将 saveFilename 制空
        saveFilename = "";
        return "forward:/user/page.action";
    }

}
